<template>
  <div>
    <TopFilter ref="topFilter" :list="topFilterList" :cols="4" labelWidth="100" @filterChange="changeHandle" @resetChange="resetHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :selectionType="'single'"
      :datakey="'rows'"
      :isSelectColumn="false"
      :onSyncTableData="tableChangeFun"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" :click="downHandle">导出</multiuse-button>
      </template>
    </FilterTable>

    <!-- 选择经销商 -->
    <BaseDialog :visible.sync="selectDelearFlag" :title="'服务中心选择'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DealerList @close="Delearclose" @save="Delearsave"></DealerList>
    </BaseDialog>

    <Drawer :visible.sync="action.visible" :title="action.title" width="70%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OrderPanel :type="action.type" :rowData="action.data" :chargePartition="chargePartition" :allUser="allUser" @closeDialog="closeHandler" />
    </Drawer>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import OrderPanel from './OrderPanel';
import { queryList, exportExcel, exporturl, getBrandAll, getSeriesAll, getModelAll, getConfigAll, getColorAll, getTrimAll } from '@/api/omSale/ActualSales/RetailOrders';
import { getAllRepairMaintain, getRepairTypes, getAllUser, getAllDealer, factoryExportRepairHistory } from '@/api/repair/repairManage/repairQuery/index.js';
import Cookies from 'js-cookie';
import { getDealerLabourHourList, getAllSeries, getModelsBySeries } from '@/api/repair/repairBusiness/labourHour/index.js';
import searchDealerPanel from '@/pages/repair/mileageDateChange/mileageApprove/searchDealerPanel';
import { getPinpSelect, getChexSelect, getCheModelSelectTable,getCheModelSelect, queryModelBySeriesId } from '@/api/repair/repairReception/customer/brand.js';
import { getListService, exportRepair, exportRepairModel, updateStatesRepairItem, getCarSeries, getCarModels, sendDown } from '@/api/claim/dealer/AuthMaintenance';
import { region } from '@/api/cms-common/region'; //行政区域
import { queryChargeDifferentiationList } from '@/api/repair/repairReception/repairBusinessManger';
import { getNameByIds } from '@/api/repair/common/index.js';

export default {
  name: 'repairQuery',
  components: {
    OrderPanel,
    searchDealerPanel,
    DealerList
  },
  mixins: [dictionary, region],
  data() {
    this.BaseTable = null;
    this.allSeries = {};
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    return {
      topFilterList: this.createTopFilterList(),
      fetchApi: getAllRepairMaintain,
      selectDealerData: [],
      dealerData: [],
      selectDelearFlag: false,
      fetchParams: { xhrAbort: true },
      columns: this.createTableColumns(),
      dealerAction: { type: '', visible: false, title: '选择经销商', data: null },
      action: { type: 'add', visible: false, title: '维修工单明细', data: null },
      allUser: [],
      chargePartition: [],
      tableData: [],
      allDealer: [],
      allShortDealer: []
    };
  },
  created() {
    //this.getRepairTypesFun();
    this.getAllBrand();
    this.getAllUser();
    this.getAllDealer();
    this.queryChargeList();
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.initProvince();
    this.getAllSeries();
    // this.initQuery();
  },
  methods: {
    // 初始化查询
    async initQuery() {
      let formData = await this.$refs.topFilter.GET_FORM_DATA();
      this.fetchParams = { ...formData[1], xhrAbort: false };
    },
    // 查询收费区分
    async queryChargeList() {
      const res = await queryChargeDifferentiationList();
      if (res.resultCode == 200) {
        let items = res.data.map(x => ({ value: x.CHARGE_PARTITION_CODE + '', text: x.CHARGE_PARTITION_NAME }));
        this.chargePartition = items;
      }
    },
    SelectDelear() {
      this.selectDelearFlag = true;
    },
    //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCompanyCode: null }, { xhrAbort: false });
    },
    //保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach(item => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
    async downHandle() {
      let json = Object.assign({}, { CODE: 'CODE_00000269' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
    },
    // 获取所有的经销商
    async getAllDealer() {
      let res = await getAllDealer();
      if (res.resultCode == 200) {
        let allDealer = res.data.map(x => ({ text: x.dealerName, value: x.dealerCode + '' }));
        let allShortDealer = res.data.map(x => ({ text: x.dealerShortname, value: x.dealerCode + '' }));
        this.allDealer = allDealer;
        this.allShortDealer = allShortDealer;
         this.columns.find(x => x.dataIndex === 'ownerCode').dictItems = allDealer;
      }
    },
    async getAllUser() {
      // let res = await getAllUser();
      // if (res.resultCode == 200) {
      //   this.allUser = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      //   this.columns.find(x => x.dataIndex === 'serviceAdvisor').dictItems = this.allUser;
      //   this.columns.find(x => x.dataIndex === 'chiefTechnician').dictItems = this.allUser;
      //   this.columns.find(x => x.dataIndex === 'technician').dictItems = this.allUser;
      //   this.columns.find(x => x.dataIndex === 'balanceHandler').dictItems = this.allUser;
      // }
    },
    // 获取所有的人员
    async getNameByIds(parmas) {
      let res = await getNameByIds(parmas);
      if (res.resultCode == 200) {
        let userList = res.data.map(x => ({ text: x.employeeName, value: x.employeeId + '' }));
        this.columns.find(x => x.dataIndex === 'serviceAdvisor').dictItems = userList;
        this.columns.find(x => x.dataIndex === 'chiefTechnician').dictItems = userList;
        this.columns.find(x => x.dataIndex === 'technician').dictItems = userList;
        this.columns.find(x => x.dataIndex === 'balanceHandler').dictItems = userList;
        this.allUser = userList;
      }
    },
    dealerTranslate() {
      let userIds = [];
      this.tableData.forEach(item => {
        item.serviceAdvisor && userIds.push(item.serviceAdvisor); //服务顾问
        item.chiefTechnician && userIds.push(item.chiefTechnician); //指定技师
        item.technician && userIds.push(item.technician); //维修技师
        item.balanceHandler && userIds.push(item.balanceHandler); //结算员
      });
      if (!userIds.length) return; //执行下面语句!userIds.length为真，则执行return,并跳出。
      let newUserIds = Array.from(new Set(userIds)); // 数组去重
      let userIdsStr = newUserIds.join(',');
      if (!userIdsStr.length) return;
      this.getNameByIds({ userIds: userIdsStr });
    },
    tableChangeFun(data) {
      console.log(data);
      this.tableData = data;
      this.dealerTranslate();
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
        },
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'repairTypeCode',
          placeholder: '请选择',
          itemList: [{text:"事故",value:"B"},{text:"活动",value:"H"},{text:"首保",value:"M"},{text:"机电",value:"N"},{text:"PDS",value:"P"},
          {text:"保修",value:"X"},{text:"定保",value:"Y"}
          ]
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请输入...'
        },
        // {
        //   type: 'MULTIPLE_SELECT',
        //   label: '工单状态',
        //   fieldName: 'roStatus',
        //   placeholder: '请选择',
        //   itemList: this.createDictList(8049)
        // },
        // {
        //   type: 'SELECT',
        //   label: '是否提报索赔',
        //   fieldName: 'roClaimStatus',
        //   placeholder: '请选择',
        //   itemList: [
        //     { value: 10041001, text: '是' },
        //     { value: 10041002, text: '否' }
        //   ]
        // },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          placeholder: '请选择'
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'seriesCode',
          placeholder: '请选择...',
          initialValue: '',
          itemList: this.getCarSeriesData(),
          change: (val) => {
            console.log(val, this.topFilterList);
            if (val) {
              this.getCarModelData(val, 'edit', true);
            } else {
              this.topFilterList.find(item => item.fieldName === 'modelCode').itemList = [];
              this.topFilterList.find(item => item.fieldName === 'modelCode').initialValue = '';
            }

          }
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'modelCode',
          placeholder: '请选择...',
          itemList: [],
        },
        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '送修人',
          fieldName: 'deliverer',
          placeholder: '请输入...'
        },
        {
          type: 'RANGE_DATE',
          label: '结算日期',
          fieldName: 'balanceBeginTime|balanceEndTime',
          dateType: 'datetimerange',
          initialValue: [
            moment(new Date())
              .subtract(6, 'month')
              .format('YYYY-MM-DD 00:00:00'),
            moment(new Date()).format('YYYY-MM-DD 23:59:59')
          ],
        },
        {
          type: 'RANGE_DATE',
          label: '开单日期',
          fieldName: 'createBeginTime|createEndTime',
          dateType: 'datetimerange',
          initialValue: [
            moment(new Date())
              .subtract(6, 'month')
              .format('YYYY-MM-DD 00:00:00'),
            moment(new Date()).format('YYYY-MM-DD 23:59:59')
          ],
        },
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.isEdit(props.row)} onClick={() => this.editHandle(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },

        {
          title: '服务中心代码',
          dataIndex: 'serviceDealerCode',
          width: 150,
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '服务中心名称',
          dataIndex: 'serviceDealerName',
          width: 150,
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          // filterType: 'input',
          // render: props => {
          //   // 不能翻译就显示code
          //   let ownerShortName = props.row.ownerCode;
          //   if (this.allDealer.length) {
          //     let item = this.allDealer.find(x => x.value == props.row.ownerCode);
          //     if (item) {
          //       ownerShortName = item.text;
          //       props.row.ownerShortName = item.text; // 每一条数据增加一个字段，后台不存前端显示用
          //     }
          //   }
          //   return <span>{ownerShortName}</span>;
          // }
        },
        {
          title: '工单开单时间',
          dataIndex: 'roCreateDate',
          width: 150,
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          filterType: 'input'
        },
        {
          title: '结算时间',
          dataIndex: 'balanceTime',
          width: 150,
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          filterType: 'input'
        },
        {
          title: '工单号',
          dataIndex: 'roNo',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车牌号',
          dataIndex: 'license',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '维修类型',
          dataIndex: 'repairTypeName',
          width: 150,
          sorter: true
        },
        {
          title: '服务顾问',
          dataIndex: 'serviceAdvisorName',
          width: 150,
          sorter: true,
          dictItems: []
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主',
          dataIndex: 'ownerName',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '客户类型',
        //   dataIndex: 'ownerProperty',
        //   width: 150,
        //   sorter: true,
        //   dictItems: this.createDictList('8011')
        // },
        {
          title: '维修金额',
          dataIndex: 'repairAmount',
          width: 150,
          sorter: true,
          render: props =>{
            return <span>{Math.round(props.row.repairAmount*100)/100}</span>;
          }
        },
        {
          title: '结算金额',
          dataIndex: 'balanceAmount',
          width: 150,
          sorter: true,
          render: props =>{
            return <span>{Math.round(props.row.balanceAmount*100)/100}</span>;
          }
        },
        // {
        //   title: '收款金额',
        //   dataIndex: 'receiveAmount',
        //   width: 150,
        //   sorter: true,
        //   render: props =>{
        //     return <span>{parseInt(props.row.receiveAmount).toFixed(2)}</span>;
        //   }
        // },
        // {
        //   title: '实收维修金额',
        //   dataIndex: 'realSalesAmount',
        //   width: 150,
        //   sorter: true,
        //   render: props =>{
        //     return <span>{parseInt(props.row.realSalesAmount == null || props.row.realSalesAmount == '' ? 0.00 : props.row.realSalesAmount).toFixed(2)}</span>;
        //   }
        // },
        {
          title: '交车时间',
          dataIndex: 'deliveryDate',
          width: 150,
          sorter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '进厂行驶里程',
          dataIndex: 'inMileage',
          width: 150,
          sorter: true,
          render: props =>{
            return <span>{Math.round(props.row.inMileage*100)/100}</span>;
          }
        },
        {
          title: '预交车时间',
          dataIndex: 'endTimeSupposed',
          width: 150,
          sorter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '送修人手机',
          dataIndex: 'delivererMobile',
          width: 150,
          sorter: true
        },
        {
          title: '送修人姓名',
          dataIndex: 'deliverer',
          width: 150,
          sorter: true
        },
        {
          title: '电机号',
          dataIndex: 'machineNo',
          width: 150,
          sorter: true
        },
        {
          title: '电池编号',
          dataIndex: 'batteryNo',
          width: 150,
          sorter: true
        },
        {
          title: '发动机号',
          dataIndex: 'engineNo',
          width: 150,
          sorter: true
        },
        {
          title: '变速器号',
          dataIndex: 'gearBox',
          width: 150,
          sorter: true
        },
        {
          title: '故障现象',
          dataIndex: 'roTroubleDesc',
          width: 150,
          sorter: true
        },
        // {
        //   title: '处理结果',
        //   dataIndex: '',
        //   width: 150,
        //   sorter: true
        // },
      ];
    },

    getCarSeriesData() {
      let dataArr = [];
      let tempArr = [];
      getCarSeries().then((res) => {
        if (res.resultCode === 200) {
          res.data.forEach((item) => {
            if (item.SERIES_CODE && !tempArr.includes(item.SERIES_CODE)) {
              tempArr.push(item.SERIES_CODE);
              dataArr.push({ text: item.SERIES_CODE, value: item.SERIES_CODE, id: item.SERIES_ID });
            }
          });
          this.seriesList = dataArr;
        }
      });
      return dataArr;
    },

    getCarModelData(code, type, isTopFilter = false) {
      let series = this.seriesList.find(item => item.text === code);
      let dataArr = [];
      console.log(series)
      if (series && series.id) {
        getCarModels(series.id).then((res) => {
          console.log(res)
          if (res.resultCode === 200) {
            if (type == 'edit' && isTopFilter) {
              this.topFilterList.find(item => item.fieldName === 'modelCode').itemList = res.data.map(x => ({ text: x.MODEL_CODE1, value: x.MODEL_CODE1 }));
            }
            res.data.forEach((item) => {
              dataArr.push({ text: item.MODEL_CODE1, value: item.MODEL_CODE1 })
            })
          }
          this.modelList = dataArr;
        });
      }
    },

    async getAllSeries() {
      let res = await getChexSelect('null');
      if (res.resultCode === 200) {
        let series = res.data.map(x => {
          return { value: x.seriesCode, text: x.seriesName };
        });
        this.topFilterList.find(x => x.fieldName === 'series').itemList = series;
        this.allSeries = res.data;
      }
    },
    async getModelsBySeries(val) {
      let res = await getCheModelSelect('null', val);
      if (res.resultCode === 200) {
        let models = res.data.map(x => {
          return { value: x.modelCode, text: x.modelName };
        });
        this.topFilterList.find(x => x.fieldName === 'model').itemList = models;
      }
    },
    // 获取维修类型
    async getRepairTypesFun() {
      const res = await getRepairTypes();
      this.repairList = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
      this.topFilterList.find(x => x.fieldName === 'repairTypeCode').itemList = this.repairList;
      this.columns.find(x => x.dataIndex === 'repairTypeCode').dictItems = this.repairList;
      this.columns.find(x => x.dataIndex === 'repairTypeCode').filterItems = this.repairList;
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCompanyCode: null }, { xhrAbort: false });
    },

    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.topFilterList.find(item => item.fieldName === 'province').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      console.log(rd, 'rd:::');
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find(item => item.fieldName === 'city');
      city.itemList = cl;
      city.initialValue = '';
      //清除区县
      let district = this.topFilterList.find(item => item.fieldName === 'district');
      district.itemList = [];
      district.initialValue = '';
    },
    //初始化所在区数据
    async initDistrict(cityId) {
      if (!cityId || cityId == null || typeof cityId == 'undefined') {
        return;
      }
      let cl = this.district(cityId);
      //初始化区县，清除原值
      let district = this.topFilterList.find(item => item.fieldName === 'district');
      district.itemList = cl;
      district.initialValue = '';
    },
    // async getNameByIds(parmas) {
    //   let res = await getNameByIds(parmas);
    //   if (res.resultCode == 200) {
    //     let userList = res.data.map(x => ({ text: x.employeeName, value: x.employeeId + '' }));
    //     this.columns.find(x => x.dataIndex === 'serviceAdvisor').dictItems = userList;
    //   }
    // },
    // dealerTranslate() {
    //   let userIds = [];
    //   this.tableData.forEach(item => {
    //     userIds.push(item.serviceAdvisor);
    //   });
    //   let newUserIds = Array.from(new Set(userIds)); // 数组去重
    //   let userIdsStr = newUserIds.join(',');
    //   this.getNameByIds({ userIds: userIdsStr });
    // },
    // tableChangeFun(data) {
    //   this.tableData = data;
    //   this.dealerTranslate();
    // },
    isEdit(row) {
      // console.log(row.down_tag);
      if (row.dataSources == '10451002' && Cookies.get('dataType') === 10461001) {
        // 店端账号、并且对应主机厂数据时不可以编辑
        return true;
      } else {
        return false;
      }
    },
    addHandle() {
      this.action = { type: 'add', title: '工单明细', visible: true, data: null };
    },
    editHandle(row) {
      this.action = { type: 'edit', title: '工单明细', visible: true, data: { ...row } };
    },
    changeHandle(val) {
      // let ownerCode = this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue || '';
      // this.fetchParams = Object.assign({ ownerCode: ownerCode }, val);
      // 搜索和重置都走
      // let ss = JSON.parse(JSON.stringify(val));
      // ss.roStatus = !ss.roStatus?'':ss.roStatus.join('\',\'');
      // console.log(ss.roStatus)
      // let params = { ...this.fetchParams, ...val,...{ xhrAbort: false } };
      // if (params.ownerShortName && params.ownerShortName.length) {
      //   params.ownerCode = this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue;
      // } else {
      //   params.ownerCode = undefined;
      // }
      // params = Object.assign({page : params.pageNum},params);
      // delete params[pageNum];
      // this.fetchParams = params;
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ?  this.selectDealerData : null}, { xhrAbort: false });
      console.log(JSON.stringify(this.fetchParams)+"++++++++++++++++++++++++++++++++++++")
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeDealerDialog() {
      this.dealerAction.visible = false;
    },
    saveDealerDialog([params]) {
      this.dealerAction.visible = false;
      this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue = params.dealerCode;
      this.topFilterList.find(x => x.fieldName === 'ownerShortName').initialValue = params.dealerShortname;
    },

    closeHandler(val, type) {
      this.action.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
